package com.example.tse.rbyair.login.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tse.rbhttpservice.service.HttpService;
import com.example.tse.rbhttpservice.service.RemoteServiceFactory;
import com.example.tse.rbhttpservice.service.RemoteServiceListenerT;
import com.example.tse.rbhttpservice.service.account.model.AccountLoginRequest;
import com.example.tse.rbhttpservice.service.account.model.AccountLoginResponse;
import com.example.tse.rbyair.MainActivity;
import com.example.tse.rbyair.R;
import com.example.tse.rbyair.dialog.CheckCallDialog;
import com.example.tse.rbyair.login.ForgetPwdActivity;
import com.example.tse.rbyair.util.ClearEditText;
import com.example.tse.rbyair.util.SharedPreferenceUtils;

import org.kymjs.kjframe.log.L;
import org.kymjs.kjframe.utils.StringUtils;

import butterknife.Bind;
import butterknife.ButterKnife;

public class LoginFragment extends Fragment implements OnClickListener {

    @Bind(R.id.phoneEtxt)
    ClearEditText phoneEtxt;
    @Bind(R.id.pwdEtxt)
    ClearEditText pwdEtxt;
    @Bind(R.id.forgotPwdBtn)
    TextView forgotPwdBtn;
    @Bind(R.id.loginBtn)
    Button loginBtn;
    // 首页布局
    private View view;
    private String type0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, null);
        ButterKnife.bind(this, view);
        L.d("lichun", "LoginFragment HttpService.token:" + HttpService.token);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        this.view = view;
        ButterKnife.bind(this, view);
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        type0 = getActivity().getIntent().getStringExtra("type");
        String s = getActivity().getIntent().getStringExtra("phone");
        if (!TextUtils.isEmpty(s)) {
            phoneEtxt.setText(s);
        }

        forgotPwdBtn.setOnClickListener(this);
        loginBtn.setOnClickListener(this);

        phoneEtxt.setText(SharedPreferenceUtils.getValueByKey(getActivity(), "account"));
        pwdEtxt.setText(SharedPreferenceUtils.getValueByKey(getActivity(), "pwd"));

    }

    private boolean checkInput() {
        String telRegex = "[1][3578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3578中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位
        String pho = phoneEtxt.getText().toString().trim();
        String pwd = pwdEtxt.getText().toString().trim();

        L.d("lichun", "LoginFragment pho:" + pho);
        Boolean isPhone = StringUtils.isPhone(pho);

        if (TextUtils.isEmpty(pho)) {
            Toast.makeText(getActivity(), R.string.phonenoempty, Toast.LENGTH_LONG).show();
            return false;
        } else if (!pho.matches(telRegex)) {
            Toast.makeText(getActivity(), R.string.pleaseinputcorrectphone, Toast.LENGTH_LONG).show();
            return false;
        } else if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(getActivity(), R.string.pwdnoempty, Toast.LENGTH_LONG).show();
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginBtn:
                if (checkInput()) {

                    login(phoneEtxt.getText().toString().trim(), pwdEtxt.getText().toString().trim());
                }
                break;
            case R.id.forgotPwdBtn:
                Intent intent1 = new Intent(getActivity(), ForgetPwdActivity.class);
                startActivity(intent1);
                break;
            case R.id.tv_cancel:
                if (null != type0 && type0.equals("2")) {
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    intent.putExtra("TURNBACKFIRST", "1");
                    startActivity(intent);
                    getActivity().finish();
                } else {
                    getActivity().finish();
                }
                break;
        }
    }

    private void login(final String phone, final String pwd) {

        L.d("LoginFragment login:" + " phone" + phone + " pwd:" + pwd);

        HttpService.cleanToken();
        AccountLoginRequest ar = new AccountLoginRequest() {
            @Override
            public String givePhone() {
                return phone;
            }

            @Override
            public String givePassword() {
                return pwd;
            }

            @Override
            public String givePasswordEnc() {
                return "";
            }
        };

        RemoteServiceFactory.getInstance().getAccountService(getActivity()).login(ar, new RemoteServiceListenerT<AccountLoginResponse>() {


            @Override
            public void PreStart() {
                super.PreStart();

                L.d("LoginFragment PreStart HttpService.token:" + HttpService.token);
            }


            @Override
            public void onMessage(String message) {
                super.onMessage(message);
                L.d("LoginFragment message:" + message);
            }

            @Override
            public void Finish() {
                super.Finish();
                L.d("LoginFragment Finish HttpService.token:" + HttpService.token);
            }

            @Override
            public void okData(AccountLoginResponse accountLoginResponse) {
                super.okData(accountLoginResponse);

                SharedPreferenceUtils.putValueAndKey(getActivity(), "userToken", HttpService.token);

                SharedPreferenceUtils.putValueAndKey(getActivity(), "memberId", accountLoginResponse.getMemberId());
                SharedPreferenceUtils.putValueAndKey(getActivity(), "account", phoneEtxt.getText().toString().trim());
                SharedPreferenceUtils.putValueAndKey(getActivity(), "pwd", pwdEtxt.getText().toString().trim());
                SharedPreferenceUtils.putValueAndKey(getActivity(), "alias", accountLoginResponse.getAlias());


                SharedPreferenceUtils.putValueAndKey(getActivity(), "isLoaded", "1");
//                AppInforUtil.isExited = false;

                if (null != type0 && type0.equals("1")) {
                    getActivity().finish();
                } else if (null != type0 && type0.equals("2")) {
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    intent.putExtra("TURNBACKFIRST", "1");
                    startActivity(intent);
                    getActivity().finish();

                } else {
                    getActivity().finish();
                }

                if (accountLoginResponse.getIs_new().equals("1")) {  //新用户

                    CheckCallDialog checkCallDialog = new CheckCallDialog();
                    checkCallDialog.setOnOkClickLitener(new CheckCallDialog.OnOkClickLitener() {
                        @Override
                        public void OK() {
                            if (null != type0 && type0.equals("1")) {
                                getActivity().finish();
                            } else if (null != type0 && type0.equals("2")) {
                                Intent intent = new Intent(getActivity(), MainActivity.class);
                                intent.putExtra("TURNBACKFIRST", "1");
                                startActivity(intent);
                                getActivity().finish();

                            } else {
                                startActivity(new Intent(getActivity(), MainActivity.class));
                                getActivity().finish();
                            }
                        }

                        @Override
                        public void Cancel() {
                            L.d("lichun", "MeFragment Cancel:");
                        }
                    });

                    checkCallDialog.show(getFragmentManager(), "");
//                startActivity(new Intent(getActivity(),));
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
